<template>
    <div class="content">
        <el-form label-width="100px" :model="formInline" ref="formInline" :label-position="labelPosition" :rules="rules">
            <div class="box">
                <div class="appTitle">
                    <h3>添加食谱</h3>
                </div>   
                <!-- 选择学校和周期 start-->           
                <div class="appTop"><P>周期</p></div>
                <el-row :gutter="41">
                    <!-- <el-col :span="9" class="form-col-padding-left">
                        <el-form-item label="选择学校" class="form-label-padding" prop="schoolName" >
                           <school v-model="formInline.schoolName" style="width:100%" @change="schoolChange"></school>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="9">
                        <el-form-item label="选择周期" class="form-label-padding">
                            <el-select v-model="formInline.cycle" style="width:200px;" >
                                <el-option
                                    v-for="item in formInline.cycleList"
                                    :key="item.id"
                                    :label="item.label"
                                    :value="item.id"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 选择学校和周期 end-->

                <!-- 选择模板 start -->
                <div class="appTop"><P>选择模板</p></div>
                <el-row :gutter="20">
                    <el-col :span="11" style="min-width:568px;">
                        <el-form-item label="选择历史菜谱" class="form-label-padding">
                            <el-select v-model="formInline.recipeHistory" style="width:100%" placeholder="请选择历史菜谱" @change="handleHistoryRecipe">
                                <el-option
                                    v-for="item in formInline.recipeHistoryList"
                                    :key="item.pId"
                                    :label="item.suitTime"
                                    :value="item.pId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 选择模板 end -->

                <!-- 添加菜谱 start -->
                <div class="appTop"><P>添加菜谱</p></div>
                <div class="form-row-list">
                    <ul>
                    <li v-for="(item,index) in formInline.weekList" class="form-col-padding-left" :key="index">
                        <p class="form-date">{{convertWeekToWeekName(item.sWeekday)}}</p>              
                        <el-row :gutter="20" >
                            <el-col :span="22" >
                                <el-form-item label="添加早餐" class="form-label-padding" :prop="'weekList.' + index + '.sBreakfastContent'"  :rules="{ pattern: /^[\u4e00-\u9fa5a-zA-Z0-9,]+$/, message: '请输入字母，数字，汉字不能有空格，多个名称请以英文逗号分隔', trigger: 'blur' }">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于120个字" >
                                        <el-input v-model="item.sBreakfastContent" placeholder="请输入早餐（ 若同时输入多项早餐，以英文“,” 做分隔 ）" width="100%" :maxlength="120" slot="reference"></el-input>
                                    </el-popover> 
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20" >
                             <el-col :span="22" >
                                <el-form-item label="添加午餐" class="form-label-padding" :prop="'weekList.' + index + '.sLunchContent'" :rules="{ pattern: /^[\u4e00-\u9fa5a-zA-Z0-9,]+$/, message: '请输入字母，数字，汉字不能有空格，多个名称请以英文逗号分隔', trigger: 'blur' }" >
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于120个字" >
                                        <el-input v-model="item.sLunchContent" placeholder="请输入午餐（ 若同时输入多项午餐，以英文 “,” 做分隔 ）" width="100%" :maxlength="120" slot="reference"></el-input>
                                    </el-popover> 
                                </el-form-item>
                            </el-col>
                        </el-row>
                         <el-row :gutter="20" >
                             <el-col :span="22">
                                <el-form-item label="添加晚餐" class="form-label-padding" :prop="'weekList.' + index + '.sDinnerContent'" :rules="{ pattern: /^[\u4e00-\u9fa5a-zA-Z0-9,]+$/, message: '请输入字母，数字，汉字不能有空格，多个名称请以英文逗号分隔', trigger: 'blur' }" >
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于120个字" >
                                        <el-input v-model="item.sDinnerContent" placeholder="请输入晚餐（ 若同时输入多项晚餐，以英文 “,” 做分隔 ）" width="100%" :maxlength="120" slot="reference"></el-input>
                                    </el-popover> 
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </li>
                    </ul>
                </div>
                <!-- 添加菜谱 end -->

                <!-- 按钮 start-->
                <div class="footer">
                    <el-button @click="goBack">取消</el-button>    
                    <el-button type="primary" @click="submitForm('formInline')" :disabled="btnDisabled">确认</el-button>
                </div>
                <!-- 按钮 end-->

            </div>
         </el-form>
    </div> 
</template>

<script>
// import moment from 'moment';
import { mapGetters } from 'vuex';
import school from 'components/SchoolClasss/school';
import {
  addNewRecipe,
  checkRecipeCycle,
  getRecipeHistoryList,
  getRecipeDetailByRecipeId
} from 'api/recipeManage';

export default {
    name: 'addNewRecipeList',
    components: {school},
    data() {
        return {
            labelPosition: 'left', // label左对齐
            rules: {
        // 验证规则
                schoolName: { required: true, message: '请输入学校名称', trigger: 'blur' }
            },
            formInline: {
                // schoolName: '', // 学校名称
                // schoolId: '378170406713950208', // 学校ID
                cycleList: [
                    {
                        id: '1',
                        label: '本周'
                    },
                    {
                        id: '2',
                        label: '下周'
                    }
                ],
                cycle: '1', // 菜谱周期
                recipeHistory: '', // 历史菜谱
                schoolList: [],
                recipeHistoryList: [], // 历史菜谱
                weekList: []
                // startTime: null, // 食谱的开始时间
                // endTime: null   // 食谱的结束时间
            },
            schoolLoading: false, // 搜索学校名称的加载
            btnDisabled: false // 禁用按钮
        };
    },
    created() {
    // 设置周期
        this.setRecipeCycle();

    // 判断可以发布什么时候的食谱
        this.checkCycle()
    
    // 获取历史菜谱
        this.getHistoryRecipeList();

    },
    computed: {
        ...mapGetters([
            'schoolId',
            'schoolName'
        ])

    },
    watch: {
    // 监听周期的变化设置默认选中
        ['formInline.cycleList'](val) {
            this.formInline.cycle = val[0].id;
        }
    },
    methods: {
    // 设置周期
        setRecipeCycle() {
            for (let i = 0; i < 7; i++) {
                let item = {
                    sWeekday: '',
                    sBreakfastContent: '',
                    sLunchContent: '',
                    sDinnerContent: ''
                };
                item.sWeekday = (i + 1) + '';
                // //console.log(typeof item.sWeekday);
                this.formInline.weekList.push(item);
            }
        },


    // 功能：获取历史菜谱
        getHistoryRecipeList() {
            getRecipeHistoryList(this.schoolId).then(res => {
                // //console.log('res', res);
                this.formInline.recipeHistoryList = res.data.content;
                this.formInline.recipeHistoryList.unshift({pId: 0, suitTime: '请选择'});
                //console.log('菜谱', this.formInline.recipeHistoryList);
            });
        },

    // 功能：选择历史菜谱
        handleHistoryRecipe() {
            // //console.log('1111111111111', this.formInline.recipeHistory);
            let list = this.formInline.weekList;
            if (this.formInline.recipeHistory == 0) {
                for (let i = 0; i < list.length; i++) {
                    list[i].sBreakfastContent = '';
                    list[i].sLunchContent = '';
                    list[i].sDinnerContent = '';
                }               
            } else {
                 // 调用接口：根据食谱ID获取食谱详情
                getRecipeDetailByRecipeId(this.formInline.recipeHistory).then(res => {
                // //console.log('___________', res);
                    let list = res.data.content;
                    for (let i = 0; i < list.length; i++) {
                        this.formInline.weekList[i].sBreakfastContent = '';
                        this.formInline.weekList[i].sLunchContent = '';
                        this.formInline.weekList[i].sDinnerContent = '';

                        let index = list[i].num - 1;
                        this.formInline.weekList[index].sBreakfastContent =
                         list[i].cookbookDetails.sBreakfastContent;
                        this.formInline.weekList[index].sLunchContent =
                         list[i].cookbookDetails.sLunchContent;
                        this.formInline.weekList[index].sDinnerContent =
                         list[i].cookbookDetails.sDinnerContent;
                    }
                });
            }
            
        },

         // 判断可以发布什么时候的食谱
        checkCycle() {
            // 设置周期
            this.formInline.cycleList = [
                {
                    id: '1',
                    label: '本周'
                },
                {
                    id: '2',
                    label: '下周'
                }
            ]
            // 调用接口
            checkRecipeCycle(this.schoolId).then(res => {
                if (res.data.status == 200) {
                    // //console.log('发布周期', res);
                    let flag = res.data.content;
                    // //console.log(flag);
                    let empty = false;
                    switch (flag) {
                        case 1: // 本周发布了
                            this.formInline.cycleList.splice(0, 1);
                            break;
                        case 2: // 下周发布了
                            this.formInline.cycleList.splice(1, 1);
                            break;
                        case 3: // 都发布了
                            empty = true;
                            break;
                        default:
                            // 都没有发布
                            break;
                    }
                    if (empty) {
                        this.$alert('您已经发布本周及下周食谱！', ' ', {
                            confirmButtonText: '确定',
                            callback: action => {
                                this.$router.push({path: '/recipe'});
                            }
                        });
                    }
                }
            });
        },

         // 确认
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    
                    // 判断至少填写了一个食谱
                    let flag = false;
                    for (let i = 0; i < this.formInline.weekList.length; i++) {
                        if (
                            this.formInline.weekList[i].sBreakfastContent.length != 0 ||
                            this.formInline.weekList[i].sLunchContent.length != 0 ||
                            this.formInline.weekList[i].sDinnerContent.length != 0
                            ) {
                            flag = true;
                            break;
                        }
                    }
                    if (flag) {
                        // 按钮禁用
                        this.btnDisabled = true;
                         // 当前时间
                        // let now = moment().format('YYYY-MM-DD HH:mm:ss');
                        
                        // 获取开始时间和结束时间
                        // this.setStartEndTime();


                        // 去除多余的逗号分割符
                        this.cancelQueto();

                        // 调用接口
                        addNewRecipe(this.formInline.cycle, this.schoolId, this.formInline.weekList).then(res => {       
                            if (res.data.status == 200) {      
                                let resultFlag = res.data.content;
                                if (resultFlag) {
                                    this.$message({
                                        message: '发布成功！',
                                        type: 'success'
                                    });
                                    this.$router.push({path: '/recipe/list'});
                                    this.$store.dispatch('UpdateCache');
                                } else {
                                    this.$message.error('发布失败!');
                                }
                            }
                        })
                        .catch(() => {
                            this.btnDisabled = false;
                        })
                    } else {
                        this.$confirm('您还未填写食谱,无法进行发布！', ' ', {
                            confirmButtonText: '确定'
                        });
                    }
                }
            });
        },
        
        // 功能：转换星期
        convertWeekToWeekName(item) {
            return '周' + ['一', '二', '三', '四', '五', '六', '日'][item - 1];
        },

        // 获取本周/下周的开始时间和结束时间
        // setStartEndTime() {
        //     if (this.formInline.cycle == '2') {
        //         if (moment().day() == 0) {
        //             this.formInline.startTime = moment(moment().day(+1)).format('YYYY-MM-DD');
        //             this.formInline.endTime = moment(moment().day(+7)).format('YYYY-MM-DD');
        //         } else {
        //             this.formInline.startTime = moment(moment().day(+8)).format('YYYY-MM-DD');
        //             this.formInline.endTime = moment(moment().day(+14)).format('YYYY-MM-DD'); 
        //         }
        //     } else {
        //         if (moment().day() == 0) {
        //             //console.log('8888888');
        //             this.formInline.startTime = moment(moment().day(-6)).format('YYYY-MM-DD');
        //             this.formInline.endTime = moment().format('YYYY-MM-DD');  
        //             //console.log('moment1', moment(moment().day(+14)).format('YYYY-MM-DD'));
        //             //console.log('moment', moment().format('YYYY-MM-DD'));              
        //         } else {
        //             this.formInline.startTime = moment(moment().day(1)).format('YYYY-MM-DD');
        //             this.formInline.endTime = moment(moment().day(7)).format('YYYY-MM-DD'); 
        //         }
        //     }         
        // },

        // 将填写的早中晚餐多余的逗号删除
        cancelQueto() {
            let pattern = /([\u4e00-\u9fa50-9a-zA-Z]+)(?=,)?/g;
            for (let i = 0 ; i < this.formInline.weekList.length ; i++) {
                let item = this.formInline.weekList[i];
                //console.log(item.sBreakfastContent.match(pattern));
                if (item.sBreakfastContent !== '') {
                    item.sBreakfastContent = item.sBreakfastContent.match(pattern).join(',');
                }
                if (item.sLunchContent !== '') {
                    item.sLunchContent = item.sLunchContent.match(pattern).join(',');
                }
                if (item.sDinnerContent !== '') {
                    item.sDinnerContent = item.sDinnerContent.match(pattern).join(',');
                }
            }
        },
        // 取消返回
        goBack() {
            this.$router.go(-1);
        }

    }
};
</script>


<style lang="scss">
</style>

<style lang="scss" scoped>
.content {
  padding: 0 50px;
  background: #fff;
  box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  ul,li{
      list-style:none;
  }
  .form-label-padding {
    padding-left: 16px;
  }

  .box {
    padding-bottom: 10px;
    background: #fff;
    .appTitle {
        padding-top:8px;
        text-align: center;
        font-size: 18px;
        color: #333;
        line-height: 72px;
        font-weight: bold;
        font-family: Microsoft YaHei;
        border-bottom: 1px solid #ddd;
    }

    .appTop {
      padding: 40px 0 20px 0px;
      margin-bottom: 5px;
      position: relative;
      font-size: 14px;

      p {
        margin-left: 16px;
      }

      &:before {
        content: "";
        float: left;
        border-radius: 2px;
        width: 4px;
        height: 15px;
        background: #ff5e2c;
        margin-top: 3px;
      }
    }
    .form-row-list{
        width: 100%;
        ul{
            overflow: hidden;
            li{
                float: left;
                width: 50%;
                height:246px;
                min-width: 600px;
            }
        }
    }
    .form-col-padding-left {
      // margin-right: 15em;
    //   margin-bottom: 20px;
    }
    .form-col-padding-left:nth-of-type(2n) {
      margin-right: 0px;
    }
    .form-date {
      padding: 14px 0 35px 16px;
      font-size: 14px;
      color: #333;
    }

    .footer {
      text-align: center;
      margin: 80px 0 40px 0;

      .el-button {
        padding: 10px 30px;
      }
    }
  }
}
</style>